//
//  YSGNurseAppointmentInfoController.swift
//  EyeVisionForPatients
//
//  Created by liuyutian on 2022/3/7.
//  Copyright © 2022 QDSG. All rights reserved.
//

import UIKit

class YSGNurseAppointmentInfoController: BaseViewController {

    var viewModel : YSGNurseAppointmentInfoViewModel = YSGNurseAppointmentInfoViewModel.init()
    var model: YSGNurseAppointmentModel?
    var Toll : String?
    var distance : NSInteger?
    var mapModel : AMapTip?
    var fareItemCode : String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalTo(view.safeAreaLayoutGuide).priority(.low)
            make.bottom.equalToSuperview()
        }
        
        viewModel.mapModel = self.mapModel
        viewModel.loadFamilyMemberList {[weak self] models in
            if (models.count > 0){
                
                //只有1个默认选中
                if models.count == 1 {
                    self?.familyVc(FamilyViewController(), didSelected: FamilyRowViewModel(family: models.first!))
                }
                self?.tableView.reloadData()
            }
        }
        viewModel.dataSource["chargeItemCode"] = model?.chargeItemCode

        viewModel.dataSource["orderAmount"] = String(format: "%.0f",(Toll?.floatValue ?? 0) + (model?.price?.floatValue ?? 0)*100 )
        viewModel.dataSource["distance"] = String(format: "%.2f", distance ?? "0")
        viewModel.dataSource["fare"] = Toll ?? ""
        viewModel.dataSource["hasFare"] = "1"
        viewModel.dataSource["number"] = "1"
        viewModel.dataSource["price"] = String(format: "%.0f", (model?.price?.floatValue ?? 0)*100)
        viewModel.dataSource["chargeItemName"] = model?.chargeItemName
        viewModel.dataSource["chargeItemType"] = model?.chargeItemType
        viewModel.dataSource["unit"] = "分"
        viewModel.dataSource["longitude"] = self.mapModel?.location.longitude
        viewModel.dataSource["latitude"] = self.mapModel?.location.latitude
        viewModel.dataSource["fareItemCode"] = fareItemCode
    }
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.backgroundColor = .background
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.allowsSelection = false
        tableView.tableHeaderView = headerview
        tableView.tableFooterView = footerView
        
        
        return tableView
    }()
    private lazy var headerview: UIView = {
        let headView = UIView(frame: CGRect(x: 0, y: 0, width: screenW, height: 65))
        headView.backgroundColor = .clear
        
        let imageView = UIImageView(frame: CGRect(x: 25, y: 10, width: 10, height: 11))
        imageView.image = UIImage(named: "nurse_tip")
        headView.addSubview(imageView)
        
        let label = UILabel(frame: CGRect(x: 39, y: 0, width: 200, height: 30))
        label.font = .systemFont(ofSize: 10)
        label.textColor = .init(hex: "#FA9D65")
        label.text  = "目前仅支持15公里范围内的上门护理"
        headView.addSubview(label)
        
        
        
        let placeImageView = UIImageView(frame: CGRect(x: 15, y: 34, width: 15, height: 19))
        placeImageView.image = UIImage(named: "nurse_place")
        headView.addSubview(placeImageView)
        
        let placeLabel = UILabel(frame: CGRect(x: 35, y: 30, width: 200, height: 30))
        placeLabel.font = .systemFont(ofSize: 10)
        placeLabel.textColor = UIColor.textGray
        placeLabel.text  = mapModel?.name
        headView.addSubview(placeLabel)
        
        return headView
    }()
    
    private lazy var footerView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: screenW, height: 150))
        view.backgroundColor = UIColor.clear
        let appointmentButton = UIButton()
        view.addSubview(appointmentButton)
        appointmentButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(32)
            make.right.equalToSuperview().offset(-32)
            make.top.equalToSuperview().offset(25)
            make.height.equalTo(49)
        }
        appointmentButton.setTitle("下一步", for: .normal)
        appointmentButton.titleLabel?.font = UIFont(name: "PingFangSC-Semibold", size: 16)
        appointmentButton.setTitleColor(UIColor.white, for: .normal)
        appointmentButton.backgroundColor = UIColor.mainColor
        appointmentButton.layer.cornerRadius = 24
        appointmentButton.layer.masksToBounds = true
        appointmentButton.addTarget(self, action: #selector(nextButtonClick(_:)), for: .touchUpInside)

        return view
    }()

 
    @objc func nextButtonClick(_ sender : UIButton)
    {
        if viewModel.dataSource.values.count < 25 {
            if viewModel.dataSource.keys.contains("isSuture") && viewModel.dataSource["isSuture"] as! String == "0" && !viewModel.dataSource.keys.contains("suturePosition") && viewModel.dataSource.values.count == 24{
                requestListAdd()
                return
            }
            
            HUDTool.showError(message: "请完善信息")
        }else{
            sender.isUserInteractionEnabled = false
            requestListAdd()
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                sender.isUserInteractionEnabled = true
            }
        }
    }
    
    func requestListAdd(){
        HUDTool.showActivity()
        
        viewModel.appointment_projectList_add {[weak self] model, msg, code in
            HUDTool.hideActivity()
            switch code {
            case .success:
                self?.pushOrderDetailsVc(model!)
            case .failure:
                HUDTool.showError(message: msg)
            }
        }
    }
    
    func pushOrderDetailsVc(_ model : YSGNurseAppointmentAddModel){
        let vc = YSGNurseAppointmentOrderDetailsController()
        vc.appointmentId = model.appointmentId ?? ""
        vc.orderId  = model.orderId ?? ""
        navigationController?.pushViewController(vc, animated: true)
    }
    
}

extension YSGNurseAppointmentInfoController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.sectionCount()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return  viewModel.sectionRowCount(_secion: section)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let array = Bundle.main.loadNibNamed("YSGNurseAppointmentInfoCell", owner: self, options: nil)
        
        
        let model : YSGNurseAppointmentInfoModel = viewModel.sectionData(_secion: indexPath.section)[indexPath.row]
        switch model.type{
        case .inputType:
            let cell = array?[2] as! YSGNurseAppointmentInfoCell
            cell.viewModel = viewModel
            cell.config(_model: model)
            return cell
        case .selectType:
            let cell = array?[1] as! YSGNurseAppointmentInfoCell
            cell.viewModel = viewModel
            cell.config(_model: model)
            cell.delegate = self
            return cell
        case .timeType:
            let cell = array?[0] as! YSGNurseAppointmentInfoCell
            cell.viewModel = viewModel
            cell.config(_model: model)
            return cell
        default :
            let cell = array?[0] as! YSGNurseAppointmentInfoCell
            cell.viewModel = viewModel
            cell.config(_model: model)
            return cell
        }
        
    }
}

extension YSGNurseAppointmentInfoController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        
        let titleString = viewModel.sectionTitleName(_secion: section)
        
        if titleString.count == 0{
            return nil
        }
        
        let view = UIView(frame: CGRect(x: 0, y: 0, width: screenW, height: 31))
        let label = UILabel(frame: CGRect(x: 17, y: 0, width: 100, height: 21))
        
        
        let attrString = NSMutableAttributedString(string: viewModel.sectionTitleName(_secion: section))
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont(name: "PingFangSC-Semibold", size: 15),.foregroundColor: UIColor(hex: "#4E7DFB")]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        label.attributedText = attrString
        view.addSubview(label)
        
        
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return viewModel.rowHeight(_style: viewModel.sectionData(_secion: indexPath.section)[indexPath.row].style ?? .normolStyle)
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return viewModel.sectionTitleName(_secion: section).count > 0 ? 31 : 0.001
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
}

extension YSGNurseAppointmentInfoController:YSGNurseAppointmentInfoCellDelegate,FamilyViewControllerDelegate{
    func YSGNurseAppointmentInfoCellClick( didSelected model: YSGNurseAppointmentInfoModel){
        let familyVc = FamilyViewController()
          familyVc.delegate = self
          navigationController?.pushViewController(familyVc, animated: true)
        viewModel.model = model
    }
    func familyVc(_ vc: FamilyViewController, didSelected vm: FamilyRowViewModel){
        
    
        let patientModel : YSGNurseAppointmentInfoModel = viewModel.sectionData(_secion : 0)[1]
        
        viewModel.dataSource["patientId"] = vm.patientId
        patientModel.value = vm.name
        
        let medicalCardModel : YSGNurseAppointmentInfoModel = viewModel.sectionData(_secion : 0)[2]
        
        if vm.family.isBindingCard == 1{
            medicalCardModel.value = "自费卡"
            viewModel.dataSource["medicalCardId"] = "2"
        }else if vm.family.isBindingCard == 2{
            medicalCardModel.value = "医保卡"
            viewModel.dataSource["medicalCardId"] = "1"
        }
        
        tableView.reloadData()
    }
}
